using System.Collections;
using System.Collections.Generic;
using BehaviorDesigner.Runtime;
using UnityEngine;
using BehaviorDesigner.Runtime.Tasks;

public class Chase : EnemyAction
{
    private bool getTarget;
    private Vector3 endPos;
    
    private Vector2 dir;
    private float speed;
    
    private Vector3 startPos;
    
    public bool canWait;
    private float canWaitTime;
    
    public override void OnStart()
    {
        canWaitTime = Settings.protalWaitCount;
        endPos = _find.targetPos;
        startPos = transform.position;
        dir = (endPos - startPos).normalized;
        transform.localScale = new Vector3(dir.x > 0 ? 1 : -1, 1, 1);
        speed = Settings.chasespeed;
        getTarget = false;
    }

    public override TaskStatus OnUpdate()
    { 
        if (Mathf.Abs(transform.position.x - endPos.x) <= 0.1)
        {
            if (canWaitTime <= 0 && !_find.find)return TaskStatus.Failure;
            rb.velocity = Vector2.zero;
            getTarget = true;
            canWaitTime -= Time.deltaTime;
        }
        else if (_find.find) return TaskStatus.Success;
        
        return TaskStatus.Running;
    }

    public override void OnFixedUpdate()
    {
        if(!getTarget)
            Move();
    }
    
    protected void Move()
    {
        rb.velocity = new Vector2(dir.x * speed * Time.deltaTime, rb.velocity.y);
    }
}
